import argparse
from tqdm import tqdm

def read_hex_from_file(file_path):
    # 打开文件，以二进制模式('rb')读取
    with open(file_path, 'rb') as file:
        # 读取整个文件内容
        byte_content = file.read()
    
    # 将每个字节转换为16进制形式
    hex_values = []
    for byte in byte_content:
        # 将每个字节转换为16进制，格式化为两位数
        hex_value = format(byte, '02X')
        hex_values.append(hex_value)
    return hex_values

def bit2rbt(bit_file_path,rbt_file_path):
    # 读取码流文件并以十六进制大写的方式存储
    hex_values = read_hex_from_file(bit_file_path)
    data = " ".join(hex_values)
    
    startLoc = 0
    endLoc = 12
    length = len(data)
    # 十六进制
    list16 = []
    # 计算循环的次数
    total_iterations = (length - length % 12) // 12

    with tqdm(total=total_iterations, desc="Converting") as pbar:
        while endLoc <= length-length%12:
            line = data[startLoc:endLoc-1]
            line = line.split(' ')
            lineList = []
            for item in line:
                lineList.append(item[0])
                lineList.append(item[1])
            list16.append(lineList)
            startLoc = endLoc
            endLoc += 12
            pbar.update(1)  # 更新进度条
    line = data[startLoc:]
    line = line.split(' ')
    lineList = []
    for item in line:
        lineList.append(item[0])
        lineList.append(item[1])
    list16.append(lineList)
    
    list2 = []
    # 使用 tqdm 包装 list16 以显示进度条
    with tqdm(total=len(list16), desc="Storing") as pbar:
        for line in list16:
            lineList = ""
            for i in line:
                a = i
                a = int(a, 16)  # 先把16进制转10进制
                a = bin(a)  # 再把10进制数转2进制
                lineList += a[2:].zfill(4)
            list2.append(lineList)
            pbar.update(1)  # 更新进度条
    f = open(rbt_file_path,'w')
    for line in list2:
        f.write(str(line)+'\n')
    f.close()

# bit_file_path = r"C:\Users\DELL\Desktop\bit_rbt_bin\top2.bit"
# rbt_file_path = r"C:\Users\DELL\Desktop\bit_rbt_bin\top2.rbt"

def main():
    parser = argparse.ArgumentParser(description="Convert .bit file to .rbt")
    parser.add_argument('bit_file_path', type=str, help="input .bit file path")
    parser.add_argument('rbt_file_path', type=str, help="output .rbt file path")
    
    args = parser.parse_args()
    
    bit2rbt(args.bit_file_path, args.rbt_file_path)

if __name__ == "__main__":
    main()